package models;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

@Entity
@DiscriminatorValue(value="2")
public class FoodCourt extends Place {
	@OneToMany(cascade=CascadeType.PERSIST, orphanRemoval=true, fetch=FetchType.LAZY)
	@JoinColumn(name = "parent_id")
	private Set<Establishment> establishments;

	public Set<Establishment> getEstablishments() {
		return establishments;
	}
	
	public void setEstablishments(Set<Establishment> establishments) {
		this.establishments = establishments;
	}
	
	@Override
	protected String getType() {
		return "multi";
	}
	
	@Override
	public JsonSerializer<Collection<FoodCourt>> getPlacesSerializer() {
		return new FoodCourtsJsonSerializer();
	}
	
	@Override
	public JsonSerializer<FoodCourt> getPlaceSerializer() {
		return new FoodCourtJsonSerializer();
	}
	
	public static class FoodCourtsJsonSerializer extends PlacesJsonSerializer<FoodCourt> {
		@Override
		public JsonElement serialize(Collection<FoodCourt> foodCourts, Type type,
				JsonSerializationContext context) {
			return super.serialize(foodCourts, type, context);
		}
	}
	
	public static class FoodCourtJsonSerializer extends PlaceJsonSerializer<FoodCourt> {
		@Override
		public JsonElement serialize(FoodCourt foodCourt, Type type,
				JsonSerializationContext context) {
			JsonObject json = (JsonObject) super.serialize(foodCourt, type, context);
			JsonArray establishments =  new JsonArray();
			
			for (Establishment establishment : foodCourt.getEstablishments()) {
				establishments.add(establishment.getPlaceSerializer().serialize(establishment, type, context));
			}
			
			json.add("establishments", establishments);
			return json;
		}
	}
}
